package com.fingard.dsp.bank.directbank.bozz11;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.FtpReceiver;
import com.fingard.net.MixFtp;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.text.MessageFormat;

/**
 * 郑州银行银保通
 * 
 * @author Cruise
 * @date 2019/6/27
 */
public class BOZZ11BatPayRec extends BOZZ11Base implements IBatPayRec {
	@Override
	public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988)
			throws Exception {
		return d_BatPayRec(p_req1988);
	}

	@Override
	public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998)
			throws Exception {
		return d_QryBatPayRec(p_req1998);
	}

	@Override
	public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188)
			throws Exception {
		return d_BatPayRec(p_req9188);
	}

	@Override
	public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198)
			throws Exception {
		return d_QryBatPayRec(p_req9198);
	}

	/**
	 * 批量代收付提交
	 * 
	 * @param p_reqBat
	 * @return
	 * @throws Exception
	 */
	public RetAtsBatPayRec d_BatPayRec(ReqBatPayRec p_reqBat) throws Exception {
		RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
		retAts.reqSeqID = p_reqBat.reqBatchNO;

		try {
			StringBuilder sbFileContent = new StringBuilder();

			String tmpPaySendDate = Format.Date8Format.format(p_reqBat
					.getPayDateTime());
			// 汇总信息：INSURE|保险公司类别（4 位）|批扣申请日期（8 位字节）|总笔数（4
			// 位字节）|总金额（16位字节,单位元）|合同号（10 位字节）|\n
			String totalNum = leftFill(p_reqBat.totalNum, 4);
			String totalAmt = leftFill(p_reqBat.totalAmt, 16);
			String contractNo = leftFill(
					getBankConfig().getMapValueByKey("contractNoMapping",
							p_reqBat.ownAct), 10);
			String tmpReqHeader = MessageFormat.format(
					"INSURE|{0}|{1}|{2}|{3}|{4}|\n", bankFront.corpNo,
					tmpPaySendDate, totalNum, totalAmt, contractNo);
			sbFileContent.append(tmpReqHeader);

			// 文件明细：
			while (p_reqBat.readRecord()) {
				String oppAct = "";
				String oppName = "";
				if ("1988".equals(p_reqBat.reqHeader.transType)) {
					oppAct = p_reqBat.readedDetail.recAct;
					oppName = p_reqBat.readedDetail.recName;
				} else {
					oppAct = p_reqBat.readedDetail.payAct;
					oppName = p_reqBat.readedDetail.payName;
				}
				oppAct = leftFill(oppAct, 20);
				oppName = leftFill(oppName, 30);

				String payAmt = leftFill(p_reqBat.readedDetail.payAmount, 16);
				String postScript = leftFill(p_reqBat.readedDetail.askNumber,
						20);

				String cdFlag = "";
				String summary = "";
				if ("1988".equals(p_reqBat.reqHeader.transType)) {
					cdFlag = "0";
					summary = "代付";
				} else {
					cdFlag = "1";
					summary = "代扣";
				}
				summary = leftFill(summary, 20);

				// 明细信息:客户名称（30 位字节）|银行账号（20 位字节）|金额（16 位字节）|保单或业务号（20 位字节）|收付类型
				// 1 位字节|备注(20 位字节)|\n
				String tmpReqBodyDetail = MessageFormat.format(
						"{0}|{1}|{2}|{3}|{4}|{5}|\n", oppName, oppAct, payAmt,
						postScript, cdFlag, summary);
				sbFileContent.append(tmpReqBodyDetail);
			}
			WriteBankLogLn2("批次请求文件内容:\r\n" + sbFileContent.toString());

			//保险公司类别+"_"+"001"+"_"+日期+"_01.txt"
			// (如：1003_001_20180101_01.txt)
			String tmpBatType = p_reqBat.reqHeader.transType;
			if("1988".equals(tmpBatType)){
				tmpBatType = "02";
			}else{
				tmpBatType = "01";
			}
			String tmpUploadFileName = bankFront.corpNo + "_001_"
					+ tmpPaySendDate + "_" + tmpBatType + ".txt";
			String tmpLocalMarkPath = getTempFileDirectory() + File.separator
					+ tmpUploadFileName;
			WriteBankLogLn2("批次文件保存本机路径: " + tmpLocalMarkPath);

			if (FileHelper.existFile(tmpLocalMarkPath)) {
				retAts.respCode = "0";
				retAts.respInfo = "当天已经提交过一个批次，不允许再提交其它批次";
				retAts.reqSeqID = p_reqBat.reqBatchNO;
				retAts.transState = PaymentState.FAIL_Batch;
				retAts.payInfoCode = FailCode.E9981;
				retAts.writeRetToATS();
				return retAts;
			}
			FileHelper.writeFile(tmpLocalMarkPath, sbFileContent.toString(),
					getCharset());

			// 上送银保通服务器
			FtpSet ftpSet = bankFront.getFtpSet("bat");
			MixFtp mixFtp = new MixFtp(ftpSet);
			String sftpFilePath = StringHelper.trimEnd(ftpSet.upDir, "/") + "/"
					+ tmpUploadFileName;
			FtpReceiver ftpReceiver = mixFtp.uploadFileToDir(tmpLocalMarkPath, ftpSet.upDir, tmpUploadFileName);

			retAts.respCode = "0";
			retAts.reqSeqID = p_reqBat.reqBatchNO;
			if (!ftpReceiver.isCompleted) {
				retAts.respCode = "-1";
				retAts.respInfo = ftpReceiver.connMsg;
			} else if (ConnState.FAIL.equals(ftpReceiver.connState)) {
				retAts.respInfo = "上传失败";
				retAts.transState = "BatchFailed";
				retAts.payInfoCode = "E9999";
			} else {
				retAts.respInfo = "上传成功";
				retAts.transState = "Uploaded";
				retAts.payInfoCode = "I4001";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		retAts.writeRetToATS();
		return retAts;
	}

	/**
	 * 批量代收付状态查询
	 * 
	 * @param p_reqQryBat
	 * @return
	 * @throws Exception
	 */
	public RetAtsQryBatPayRec d_QryBatPayRec(ReqQryBatPayRec p_reqQryBat)
			throws Exception {
		RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(
				p_reqQryBat.reqHeader);
		retAts.reqSeqID = p_reqQryBat.reqBatchNO;

		try {
			// 下载文件名命名规则:保险公司类别+"_"+"002"+"_"+日期+"_01.txt"
			// (如：1003_002_20180101_01.txt)
			String tmpPaySendDate = Format.Date8Format.format(p_reqQryBat.getBgnDateTime());
			String tmpBatType = p_reqQryBat.reqHeader.transType;
			if("1988".equals(tmpBatType)){
				tmpBatType = "02";
			}else{
				tmpBatType = "01";
			}

			String tmpDownFileName = bankFront.corpNo + "_002_"	+ tmpPaySendDate + "_" + tmpBatType + ".txt";
			String tmpLocalMarkPath = createTempFileDirectory()	+ File.separator + tmpDownFileName;
			WriteBankLogLn2("批次结果文件保存本地路径: " + tmpLocalMarkPath);

			FtpSet ftpSet = bankFront.getFtpSet("bat");
			String sftpFilePath = StringHelper.trimEnd(ftpSet.downDir, "/") + "/" + tmpDownFileName;
			WriteBankLogLn2("待下载SFTP服务器文件路径:\r\n" + sftpFilePath);
			MixFtp mixFtp = new MixFtp(ftpSet);
			FtpReceiver ftpReceiver = mixFtp.downloadFileFromDir(ftpSet.downDir, tmpDownFileName, tmpLocalMarkPath);
			if (ftpReceiver.isCompleted) {
				String tmpStrRet = FileHelper.readFileText(tmpLocalMarkPath,
						getCharset());
				WriteBankLogLn2("本机批次结果文件内容:\r\n" + tmpStrRet);

				if (StringHelper.hasAnyChar(tmpStrRet)) {
					retAts.respCode = "0";

					StringReader strReader = new StringReader(tmpStrRet);
					BufferedReader tmpReader = new BufferedReader(strReader);
					tmpReader.readLine();

					while (true) {
						String eachline = tmpReader.readLine();
						if (StringHelper.isNullOrEmpty(eachline)) {
							break;
						}
						if (eachline.indexOf("|") > 0) {
							// 明细记录:客户名称（30 位字节）|银行账号（20 位字节）|金额（16
							// 位字节）|保单或业务号（20 位字节）|收付类型 1 位字节|备注(20 位字节)|处理状态(2
							// 位字节)|
							String[] bodyValues = eachline.split("\\|");
							RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();

							if (p_reqQryBat.reqHeader.transType.equals("1998")) {
								tmpRetDetail.recAct = delBlank(bodyValues[1]);
								tmpRetDetail.recName = delBlank(bodyValues[0]);
							} else if (p_reqQryBat.reqHeader.transType
									.equals("9198")) {
								tmpRetDetail.payAct = delBlank(bodyValues[1]);
								tmpRetDetail.payName = delBlank(bodyValues[0]);
							}
							tmpRetDetail.postScript = delBlank(bodyValues[3]);
							tmpRetDetail.payAmount = delBlank(bodyValues[2]);
							tmpRetDetail.result = delBlank(bodyValues[6]);
							tmpRetDetail.payInfoCode = delBlank(bodyValues[5]);
							tmpRetDetail.memo = delBlank(bodyValues[5]);

							retAts.writeRetDetail(tmpRetDetail);
						} else {
							retAts.respCode = "-1";
							retAts.respInfo = "银行返回明细数据格式非法!";
						}
					}
				} else {
					retAts.respCode = "-1";
					retAts.respInfo = "本机批次结果文件内容为空!";
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = "批次结果文件下载失败:" + ftpReceiver.connMsg;
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		retAts.writeAfterDetail();
		return retAts;
	}
}